﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Data.SqlTypes;
using Logic;
using Helper;
using DBAccess;
using WHUT;
using System.IO;

public partial class token_work : WorkBasePage
{

    readonly static AbstractLogger log = AbstractLogger.GetLogger(typeof(token_work));
    protected WorkAbstractUser wau;

    protected void Page_Load(object sender, EventArgs e)
    {
        wau = base.GetCurrentAbstractUser();

        if(!IsPostBack)
        {
            // editing ...
            hfWorkId.Value = Request.QueryString["id"];
            if (!string.IsNullOrEmpty(hfWorkId.Value))
            {
                // load the work
                Works w = Works.Load(Function.IntSafeConvert(hfWorkId.Value));
                if (w == null)
                {
                    log.Warn("no such news." + hfWorkId.Value);
                    Response.Redirect("work.aspx");
                    return;
                }

                tbName.Value = w.Name;
                tbTool.Value = w.Tool;
                tbType.Value = w.Type;
                tbUrl.Value = w.Url;
                
                if (!string.IsNullOrEmpty(w.ImgHome))
                {
                    ImgPreview.Visible = true;
                    ImgPreview.Text = " <a href='" + Function.ResolveRelURL(w.ImgHome)  + "' target='_blank'>预览</a> ";
                    //
                    tbImgHome.Value = w.ImgHome;
                }                
                

                // the literal 
                litOP.Text = "修改作品";
            }
        }
    }
    
    protected void Submit_Click(object sender, EventArgs e)
    {
        if (AddOrUpdateWork())
        {
            Function.SucessSubmitAndRedirect("token/work_list.aspx");
        }

    }

    private bool AddOrUpdateWork()
    {
        Works w = null;
        // add or edit ?
        bool _editing = false;
        if (Function.IntSafeConvert(hfWorkId.Value, Constants.INVALID_ID_NUMBER) != Constants.INVALID_ID_NUMBER)
            _editing = true;
        
        if (_editing)
        {
            w = Works.Load(Function.IntSafeConvert(hfWorkId.Value));
        }
        else
        {
            w = new Works();
        }

        w.Name = tbName.Value.Trim();
        w.Tool = tbTool.Value.Trim();
        w.Type = tbType.Value.Trim();
        w.Url = tbUrl.Value.Trim();
        w.TimeAdd = DateTime.Now;

        const string upPath = "~/token/webImgs/";

        // 是否上传新的图片 ？
        if (selImgHome.Value == "0")
        {
            //判断文件是否能够上传
            const string acceptType = ".gif|.jpg|.jpeg|.bmp|.png";
            const int maxSize = 800 * 1024;

            if (fuImgHome.HasFile)
            {
                //判断上传的文件是否超过允许大小
                if (fuImgHome.PostedFile.ContentLength > maxSize || fuImgHome.PostedFile.ContentLength < 10)
                {
                    lbTips.Text = "上传图片太大";
                    lbTips.Visible = true;
                    return false;
                }
                //判断上传的文件是否是允许的格式
                if (acceptType.IndexOf(Path.GetExtension(fuImgHome.FileName).ToLower()) < 0)
                {
                    lbTips.Text = "只能上传" + acceptType + "格式的文件";
                    lbTips.Visible = true;
                    return false;
                }

                //文件存放路径
                w.ImgHome = upPath;
                if (w.ImgHome.EndsWith("/") == false) w.ImgHome += "/";

                //判断文件夹否存在,不存在则创建
                if (Directory.Exists(MapPath(w.ImgHome)) == false)
                {
                    try { Directory.CreateDirectory(MapPath(w.ImgHome)); }
                    catch (Exception ex)
                    {
                        Function.LogError(ex, Context);
                        lbTips.Text = "无法保存图片，请察看错误日志了解详情。";
                        lbTips.Visible = true;
                        return false;
                    }
                }
                w.ImgHome += fuImgHome.GetHashCode() + Path.GetExtension(fuImgHome.FileName);
                // save 
                try { fuImgHome.SaveAs(MapPath(w.ImgHome)); }
                catch (Exception ex)
                {
                    Function.LogError(ex, Context);
                    lbTips.Text = "无法保存图片，请察看错误日志了解详情。";
                    lbTips.Visible = true;
                    return false;
                }
            }
        }
        else
        {
            // 使用已有的图片URL
            w.ImgHome = tbImgHome.Value.Trim();
        }

        string res = _editing ? w.Update() : w.Insert();

        if (res != null)
        {
            lbTips.Text = "操作失败。" + res;
            lbTips.Visible = true;
            log.Error(lbTips.Text);

            return false;
        }

        return true;
        

    }


    protected void btnCancel_Click(object sender, EventArgs e)
    {
        Response.Redirect("work_list.aspx");
    }
}
